import 'package:flutter/material.dart';
import 'package:meeting_note/database_helper.dart';
import './common.dart';
import 'dart:convert';

class FileDetailScreen extends StatefulWidget {
  final FileEntity file;

  const FileDetailScreen({super.key, required this.file});

  @override
  State<FileDetailScreen> createState() => _FileDetailScreenState();
}

class _FileDetailScreenState extends State<FileDetailScreen> {
  FileEntity? _file;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadFileDetails();
  }

  Future<void> _loadFileDetails() async {
    setState(() => _isLoading = true);
    final fileDetails = await DatabaseHelper().getFileById(widget.file.id!);
    setState(() {
      _file = fileDetails;
      _isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          title: Text(_file?.fileName ?? '文件详情'),
          bottom: const TabBar(
            tabs: [
              Tab(text: '识别文本'),
              Tab(text: '文件纪要'),
            ],
          ),
        ),
        body: _isLoading
            ? const Center(child: CircularProgressIndicator())
            : TabBarView(
                children: [
                  _buildTextContentTab(),
                  _buildSummaryTab(),
                ],
              ),
      ),
    );
  }

  Widget _buildTextContentTab() {
    if (_file == null) {
      return const Center(child: Text('无法加载文件信息'));
    }

    if (_file!.status == FileStatus.pending) {
      return const Center(child: Text('文件尚未开始处理'));
    }

    if (_file!.status == FileStatus.processing) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('正在识别中...'),
          ],
        ),
      );
    }

    if (_file!.status == FileStatus.failed) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, color: Colors.red, size: 48),
            const SizedBox(height: 16),
            Text('处理失败: ${_file!.errMsg ?? "未知错误"}'),
          ],
        ),
      );
    }

    if (_file!.textContent?.isEmpty ?? true) {
      return const Center(child: Text('暂无识别文本'));
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Text(
        _file!.textContent!,
        style: const TextStyle(
          fontSize: 16,
          height: 1.5,
        ),
      ),
    );
  }

  Widget _buildSummaryTab() {
    if (_file == null) {
      return const Center(child: Text('无法加载文件信息'));
    }

    if (_file!.summary?.isEmpty ?? true) {
      return const Center(child: Text('暂无文件纪要'));
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Text(
        _file!.summary!,
        style: const TextStyle(
          fontSize: 16,
          height: 1.5,
        ),
      ),
    );
  }
}

class BubbleMessage extends StatelessWidget {
  final String text;
  final DateTime timestamp;

  const BubbleMessage({
    super.key,
    required this.text,
    required this.timestamp,
  });

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.centerLeft,
      child: Container(
        margin: const EdgeInsets.all(8),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: Colors.blue[100],
          borderRadius: BorderRadius.circular(16),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(text),
            const SizedBox(height: 4),
            Text(
              '${timestamp.hour}:${timestamp.minute.toString().padLeft(2, '0')}',
              style: const TextStyle(fontSize: 12, color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }
}